<template>
  <div class="main-content">
    <!-- 
      平台映射页面说明：
      
      1. 数据关联关系：
         - 平台映射中的分类数据来源于平台分类管理中的对应站点分类
         - 两个页面共享同一套分类数据，确保数据一致性
      
      2. 数据来源：
         - 平台分类管理：负责抓取、维护各平台的分类数据
         - 平台映射：使用平台分类管理的数据进行映射关系配置
      
      3. 实现方式：
         - 当前使用模拟数据演示关联关系
         - 实际项目中应通过全局状态管理或API共享数据
         - 建议使用Pinia/Vuex等状态管理工具统一管理分类数据
    -->
    
    <!-- 顶部操作栏 -->
    <div class="panel">
      <div class="panel-header">
        <div class="panel-title">平台分类映射（全局管理）</div>
        <div style="display:flex;gap:10px;">
          <button class="btn-primary" @click="openPlatformModal()">新增平台</button>
          <button class="btn-primary" @click="downloadTemplate">下载导入模板</button>
          <button class="btn-primary" @click="importExcel">导入</button>
          <button class="btn-primary" @click="exportExcel">导出</button>
        </div>
      </div>
      <div class="panel-body">
        <!-- 平台管理表格 -->
        <div style="margin-bottom:18px;">
          <div style="font-weight:600;margin-bottom:6px;">平台列表：</div>
          <table style="width:100%;border-collapse:collapse;background:#f8fafc;margin-bottom:10px;">
            <thead>
              <tr style="background:#f1f5f9">
                <th style="padding:8px 8px;text-align:left;">平台ID</th>
                <th style="padding:8px 8px;text-align:left;">平台名称</th>
                <th style="padding:8px 8px;text-align:left;">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="p in platformList" :key="p.id">
                <td style="padding:6px 8px;">{{ p.id }}</td>
                <td style="padding:6px 8px;">{{ p.name }}</td>
                <td style="padding:6px 8px;">
                  <button class="action-btn" @click="editPlatform(p)">编辑</button>
                  <button class="action-btn danger" @click="deletePlatform(p.id)">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <!-- 统计信息 -->
        <div style="margin-bottom:18px;display:flex;gap:24px;align-items:center;">
          <span style="font-weight:600;">总映射数：{{ total }}</span>
          <span style="color:#2dba4e;">已映射：{{ mapped }}</span>
          <span style="color:#e63946;">未映射：{{ total - mapped }}</span>
        </div>
        <!-- 搜索栏 -->
        <div style="margin-bottom:16px;">
          <input placeholder="搜索本地分类..." v-model="search" style="padding:6px;border-radius:6px;border:1px solid #e2e8f0;width:260px;" />
        </div>
        <!-- 映射矩阵表格 -->
        <table style="width:100%;border-collapse:collapse;background:#fff;">
          <thead>
            <tr style="background:#f8fafc">
              <th style="padding:10px 8px;text-align:left;">本地分类</th>
              <th v-for="p in platformList" :key="p.id" style="padding:10px 8px;text-align:left;">{{ p.name }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="flatLocalCats.length === 0">
              <td :colspan="1 + platformList.length" style="text-align:center;color:#aaa;padding:48px 0;">暂无分类</td>
            </tr>
            <tr v-for="cat in filteredCats" :key="cat.id">
              <td style="padding:8px;font-weight:500;">{{ '— '.repeat(cat.level) + cat.name }}</td>
              <td v-for="p in platformList" :key="p.id" style="padding:8px;">
                <template v-if="findMapping(cat.id, p.id)">
                  <span class="mapping-badge" :title="(findMapping(cat.id, p.id)?.platformCategoryNames||[]).map((n,i)=>n+'('+ (findMapping(cat.id, p.id)?.platformCategoryIds?.[i]||'') +')').join(', ')">
                    <template v-for="(n,i) in findMapping(cat.id, p.id)?.platformCategoryNames || []" :key="i">
                      <span>{{ n }}<span v-if="findMapping(cat.id, p.id)?.platformCategoryIds && findMapping(cat.id, p.id)?.platformCategoryIds[i]">（{{ findMapping(cat.id, p.id)?.platformCategoryIds[i] }}）</span></span><span v-if="i < (findMapping(cat.id, p.id)?.platformCategoryNames?.length||0)-1">，</span>
                    </template>
                  </span>
                  <button class="action-btn" @click="editMapping(cat.id, p.id)">编辑</button>
                  <button class="action-btn danger" @click="deleteMapping(cat.id, p.id)">删除</button>
                </template>
                <template v-else>
                  <span style="color:#aaa;">未映射</span>
                  <button class="action-btn" @click="editMapping(cat.id, p.id)">编辑</button>
                </template>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <!-- 新增/编辑平台弹窗 -->
    <div v-if="showPlatformModal" class="modal-mask">
      <form class="modal-form" @submit.prevent="submitPlatform">
        <h2>{{ editPlatformObj ? '编辑平台' : '新增平台' }}</h2>
        <input required placeholder="平台ID（英文/拼音/唯一）" v-model="platformForm.id" :disabled="!!editPlatformObj" />
        <input required placeholder="平台名称" v-model="platformForm.name" />
        <div class="modal-actions">
          <button type="submit" class="btn-primary">{{ editPlatformObj ? '保存' : '添加' }}</button>
          <button type="button" @click="showPlatformModal = false">取消</button>
        </div>
      </form>
    </div>
    <!-- 新增/编辑映射弹窗 -->
    <div v-if="showMappingModal" class="modal-mask">
      <form class="modal-form" @submit.prevent="submitMapping">
        <h2>{{ editMappingObj ? '编辑映射' : '新建映射' }}</h2>
        <div class="form-group">
          <label>本地分类</label>
          <input :value="flatLocalCats.find(cat => cat.id == mappingForm.localCategoryId)?.name || ''" readonly />
        </div>
        <div class="form-group">
          <label>平台</label>
          <input :value="platformList.find(p=>p.id===mappingForm.platform)?.name||''" readonly />
        </div>
        <div class="form-group">
          <label>平台类目名称（多个用逗号分隔）</label>
          <input 
            placeholder="如：女装,男装" 
            v-model="mappingForm.platformCategoryNames" 
            @input="onCategoryNamesInput"
            @blur="fetchCategoryIds"
          />
          <div class="input-tip">输入类目名称后，系统会自动抓取对应的类目ID</div>
        </div>
        <div class="form-group">
          <label>平台类目ID（多个用逗号分隔）</label>
          <input 
            placeholder="如：1001,1002" 
            v-model="mappingForm.platformCategoryIds" 
            @input="onCategoryIdsInput"
            @blur="fetchCategoryNames"
          />
          <div class="input-tip">输入类目ID后，系统会自动抓取对应的类目名称</div>
        </div>
        <div class="modal-actions">
          <button type="submit" class="btn-primary">{{ editMappingObj ? '保存' : '添加' }}</button>
          <button type="button" @click="showMappingModal = false">取消</button>
        </div>
      </form>
    </div>
    <!-- 导入弹窗 -->
    <div v-if="showImportModal" class="modal-mask">
      <form class="modal-form" @submit.prevent>
        <h2>导入平台映射</h2>
        <input type="file" accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" @change="handleImportFile" />
        <div v-if="importResult" style="color:#2dba4e;margin-top:12px;">{{ importResult }}</div>
        <div class="modal-actions">
          <button type="button" class="btn-primary" @click="showImportModal = false">关闭</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import * as XLSX from 'xlsx'
// 统一声明导入弹窗和结果提示变量
const showImportModal = ref(false)
const importResult = ref('')
// mock 本地分类（树形结构）
const localCategories = [
  { id: 1, name: '服饰', children: [
    { id: 11, name: '女装', children: [] },
    { id: 12, name: '男装', children: [] },
  ]},
  { id: 2, name: '美妆', children: [] },
  { id: 3, name: '家电', children: [
    { id: 31, name: '厨房电器', children: [] },
    { id: 32, name: '生活电器', children: [] },
  ]},
  { id: 4, name: '食品', children: [] },
  { id: 5, name: '图书', children: [] },
]
function flattenCategories(cats:any[], level=0, parentName='') {
  let result:any[] = []
  for(const c of cats) {
    result.push({ ...c, level, parentName })
    if(c.children && c.children.length) {
      result = result.concat(flattenCategories(c.children, level+1, c.name))
    }
  }
  return result
}
const flatLocalCats = flattenCategories(localCategories)
// mock 平台
const defaultPlatforms = [
  { id: 'mercari', name: '煤炉' },
  { id: 'yahoo_used', name: '雅虎闲置' },
  { id: 'yahoo_auction', name: '雅虎日拍' },
  { id: 'rakuma', name: '乐天闲置' },
]
const platformList = ref([...defaultPlatforms])
// mock 映射关系
const mappings = ref([
  { id: 1, localCategoryId: 1, platform: 'mercari', platformCategoryNames: ['女装', '男装'], platformCategoryIds: ['1001', '1002'] },
  { id: 2, localCategoryId: 2, platform: 'yahoo_used', platformCategoryNames: ['个护健康'], platformCategoryIds: ['2001'] },
  { id: 3, localCategoryId: 3, platform: 'yahoo_auction', platformCategoryNames: ['电子产品', '动漫周边'], platformCategoryIds: ['3001', '3002'] },
  { id: 4, localCategoryId: 4, platform: 'rakuma', platformCategoryNames: ['母婴用品'], platformCategoryIds: ['4001'] },
])
const search = ref('')
const showPlatformModal = ref(false)
const editPlatformObj = ref<any>(null)
const platformForm = reactive({ id: '', name: '' })
const showMappingModal = ref(false)
const editMappingObj = ref<any>(null)
const mappingForm = reactive({ localCategoryId: '', platform: '', platformCategoryNames: '', platformCategoryIds: '' })
const total = computed(() => flatLocalCats.length * platformList.value.length)
const mapped = computed(() => mappings.value.length)
const filteredCats = computed(() => {
  if (!search.value) return flatLocalCats
  return flatLocalCats.filter(cat => cat.name.includes(search.value))
})
function findMapping(localCategoryId:string|number, platform:string) {
  return mappings.value.find(m => m.localCategoryId == localCategoryId && m.platform === platform)
}
function openPlatformModal(p?:any) {
  if (p) {
    editPlatformObj.value = p
    platformForm.id = p.id
    platformForm.name = p.name
  } else {
    editPlatformObj.value = null
    platformForm.id = ''
    platformForm.name = ''
  }
  showPlatformModal.value = true
}
function editPlatform(p:any) {
  openPlatformModal(p)
}
function deletePlatform(id:string) {
  if (confirm('确定要删除该平台及其所有映射吗？')) {
    platformList.value = platformList.value.filter(p => p.id !== id)
    mappings.value = mappings.value.filter(m => m.platform !== id)
  }
}
function submitPlatform() {
  if (!platformForm.id.trim() || !platformForm.name.trim()) return alert('平台ID和名称不能为空')
  if (editPlatformObj.value) {
    platformList.value = platformList.value.map(p => p.id === editPlatformObj.value.id ? { ...p, ...platformForm } : p)
  } else {
    if (platformList.value.some(p => p.id === platformForm.id)) return alert('平台ID已存在')
    platformList.value.push({ ...platformForm })
  }
  showPlatformModal.value = false
}
function editMapping(localCategoryId:number|string, platform:string) {
  const exist = mappings.value.find(m => m.localCategoryId == localCategoryId && m.platform === platform)
  editMappingObj.value = exist
  mappingForm.localCategoryId = String(localCategoryId)
  mappingForm.platform = platform
  mappingForm.platformCategoryNames = exist ? exist.platformCategoryNames.join(',') : ''
  mappingForm.platformCategoryIds = exist && exist.platformCategoryIds ? exist.platformCategoryIds.join(',') : ''
  showMappingModal.value = true
}
function deleteMapping(localCategoryId:number|string, platform:string) {
  if (confirm('确定要删除该映射？')) {
    mappings.value = mappings.value.filter(m => !(m.localCategoryId === localCategoryId && m.platform === platform))
  }
}
async function submitMapping() {
  if (!mappingForm.localCategoryId) return alert('请选择本地分类')
  
  // 检查是否至少输入了类目名称或类目ID中的一个
  const hasNames = mappingForm.platformCategoryNames.trim()
  const hasIds = mappingForm.platformCategoryIds.trim()
  
  if (!hasNames && !hasIds) {
    return alert('请至少输入平台类目名称或平台类目ID中的一个')
  }
  
  let names: string[] = []
  let ids: string[] = []
  
  if (hasNames && hasIds) {
    // 如果两个都输入了，验证数量是否一致
    names = hasNames.split(',').map(s => s.trim()).filter(Boolean)
    ids = hasIds.split(',').map(s => s.trim()).filter(Boolean)
    if (names.length !== ids.length) {
      return alert('平台类目名称和ID数量需一一对应')
    }
  } else if (hasNames) {
    // 只输入了类目名称，需要抓取对应的ID
    names = hasNames.split(',').map(s => s.trim()).filter(Boolean)
    ids = await fetchCategoryIdsFromNames(names, mappingForm.platform)
    if (ids.length === 0) {
      return alert('无法找到对应的平台类目ID，请检查类目名称是否正确')
    }
  } else if (hasIds) {
    // 只输入了类目ID，需要抓取对应的名称
    ids = hasIds.split(',').map(s => s.trim()).filter(Boolean)
    names = await fetchCategoryNamesFromIds(ids, mappingForm.platform)
    if (names.length === 0) {
      return alert('无法找到对应的平台类目名称，请检查类目ID是否正确')
    }
  }
  
  if (names.length === 0 || ids.length === 0) {
    return alert('请至少输入一个有效的平台类目信息')
  }
  
  const localCategoryIdNum = Number(mappingForm.localCategoryId)
  const existIdx = mappings.value.findIndex(m => m.localCategoryId == localCategoryIdNum && m.platform === mappingForm.platform)
  
  if (existIdx > -1) {
    mappings.value[existIdx].platformCategoryNames = names
    mappings.value[existIdx].platformCategoryIds = ids
  } else {
    mappings.value.push({ 
      id: Date.now(), 
      localCategoryId: localCategoryIdNum, 
      platform: mappingForm.platform, 
      platformCategoryNames: names, 
      platformCategoryIds: ids 
    })
  }
  
  showMappingModal.value = false
}

// 根据类目名称抓取对应的类目ID
async function fetchCategoryIdsFromNames(categoryNames: string[], platform: string): Promise<string[]> {
  console.log(`正在抓取平台 ${platform} 的类目ID，类目名称：`, categoryNames)
  
  // 从平台分类管理中获取对应平台的分类数据
  const platformCategories = getPlatformCategoriesFromManager(platform)
  
  if (!platformCategories || platformCategories.length === 0) {
    console.warn(`平台 ${platform} 没有找到分类数据`)
    return categoryNames.map(name => `NOT_FOUND_${name}`)
  }
  
  // 递归搜索分类名称，返回对应的ID
  const result: string[] = []
  
  for (const categoryName of categoryNames) {
    const foundCategory = findCategoryByName(platformCategories, categoryName.trim())
    if (foundCategory) {
      result.push(foundCategory.id)
    } else {
      result.push(`NOT_FOUND_${categoryName}`)
    }
  }
  
  return result
}

// 根据类目ID抓取对应的类目名称
async function fetchCategoryNamesFromIds(categoryIds: string[], platform: string): Promise<string[]> {
  console.log(`正在抓取平台 ${platform} 的类目名称，类目ID：`, categoryIds)
  
  // 从平台分类管理中获取对应平台的分类数据
  const platformCategories = getPlatformCategoriesFromManager(platform)
  
  if (!platformCategories || platformCategories.length === 0) {
    console.warn(`平台 ${platform} 没有找到分类数据`)
    return categoryIds.map(id => `NOT_FOUND_${id}`)
  }
  
  console.log(`平台 ${platform} 的分类数据：`, platformCategories)
  
  // 递归搜索分类ID，返回对应的名称
  const result: string[] = []
  
  for (const categoryId of categoryIds) {
    const foundCategory = findCategoryById(platformCategories, categoryId.trim())
    console.log(`搜索ID ${categoryId}，结果：`, foundCategory)
    
    if (foundCategory) {
      result.push(foundCategory.name)
    } else {
      result.push(`NOT_FOUND_${categoryId}`)
    }
  }
  
  console.log(`最终结果：`, result)
  return result
}

// 从平台分类管理中获取指定平台的分类数据
function getPlatformCategoriesFromManager(platform: string): any[] {
  /*
    重要说明：平台映射与平台分类管理的数据关联关系
    
    1. 数据来源：
       - 平台分类管理页面负责抓取和维护各平台的分类数据
       - 平台映射页面使用这些数据来配置映射关系
    
    2. 当前实现：
       - 使用模拟数据演示关联关系
       - 数据结构与平台分类管理页面保持一致
    
    3. 实际项目建议：
       - 使用Pinia/Vuex等状态管理工具统一管理分类数据
       - 创建共享的categoryStore来管理所有平台分类
       - 两个页面都从同一个数据源获取数据
       - 确保数据的一致性和实时性
    
    4. 数据结构示例：
       - 与PlatformCategoryManage.vue中的Category接口保持一致
       - 支持树形结构（如煤炉平台）和平铺结构（如其他平台）
       - 包含id、name、parentId、platform、level、children等字段
  */
  
  // 模拟从平台分类管理获取的数据结构
  const mockPlatformCategories: Record<string, any[]> = {
    'mercari': [
      {
        id: '1000',
        name: '服装配饰',
        parentId: '',
        platform: 'mercari',
        level: 1,
        children: [
          { 
            id: '1001', 
            name: '女装', 
            parentId: '1000', 
            platform: 'mercari', 
            level: 2,
            children: [
              { id: '10011', name: '上衣', parentId: '1001', platform: 'mercari', level: 3 },
              { id: '10012', name: '下装', parentId: '1001', platform: 'mercari', level: 3 },
              { id: '10013', name: '连衣裙', parentId: '1001', platform: 'mercari', level: 3 },
              { id: '10014', name: '外套', parentId: '1001', platform: 'mercari', level: 3 },
              { id: '10015', name: '套装', parentId: '1001', platform: 'mercari', level: 3 },
              { id: '10016', name: '其他', parentId: '1001', platform: 'mercari', level: 3 }
            ]
          },
          { 
            id: '1002', 
            name: '男装', 
            parentId: '1000', 
            platform: 'mercari', 
            level: 2,
            children: [
              { id: '10021', name: '上衣', parentId: '1002', platform: 'mercari', level: 3 },
              { id: '10022', name: '下装', parentId: '1002', platform: 'mercari', level: 3 },
              { id: '10023', name: '外套', parentId: '1002', platform: 'mercari', level: 3 },
              { id: '10024', name: '套装', parentId: '1002', platform: 'mercari', level: 3 }
            ]
          },
          { 
            id: '1003', 
            name: '童装', 
            parentId: '1000', 
            platform: 'mercari', 
            level: 2,
            children: [
              { id: '10031', name: '上衣', parentId: '1003', platform: 'mercari', level: 3 },
              { id: '10032', name: '下装', parentId: '1003', platform: 'mercari', level: 3 },
              { id: '10033', name: '套装', parentId: '1003', platform: 'mercari', level: 3 }
            ]
          },
          { 
            id: '1004', 
            name: '内衣', 
            parentId: '1000', 
            platform: 'mercari', 
            level: 2,
            children: [
              { id: '10041', name: '文胸', parentId: '1004', platform: 'mercari', level: 3 },
              { id: '10042', name: '内裤', parentId: '1004', platform: 'mercari', level: 3 },
              { id: '10043', name: '家居服', parentId: '1004', platform: 'mercari', level: 3 }
            ]
          },
          { 
            id: '1005', 
            name: '鞋靴', 
            parentId: '1000', 
            platform: 'mercari', 
            level: 2,
            children: [
              { id: '10051', name: '女鞋', parentId: '1005', platform: 'mercari', level: 3 },
              { id: '10052', name: '男鞋', parentId: '1005', platform: 'mercari', level: 3 },
              { id: '10053', name: '童鞋', parentId: '1005', platform: 'mercari', level: 3 }
            ]
          },
          { 
            id: '1006', 
            name: '箱包', 
            parentId: '1000', 
            platform: 'mercari', 
            level: 2,
            children: [
              { id: '10061', name: '女包', parentId: '1006', platform: 'mercari', level: 3 },
              { id: '10062', name: '男包', parentId: '1006', platform: 'mercari', level: 3 },
              { id: '10063', name: '旅行箱', parentId: '1006', platform: 'mercari', level: 3 }
            ]
          },
          { 
            id: '1007', 
            name: '配饰', 
            parentId: '1000', 
            platform: 'mercari', 
            level: 2,
            children: [
              { id: '10071', name: '帽子', parentId: '1007', platform: 'mercari', level: 3 },
              { id: '10072', name: '围巾', parentId: '1007', platform: 'mercari', level: 3 },
              { id: '10073', name: '腰带', parentId: '1007', platform: 'mercari', level: 3 }
            ]
          },
          { 
            id: '1008', 
            name: '服装配饰 - 女装', 
            parentId: '1000', 
            platform: 'mercari', 
            level: 2,
            children: [
              { id: '10081', name: '上衣', parentId: '1008', platform: 'mercari', level: 3 },
              { id: '10082', name: '下装', parentId: '1008', platform: 'mercari', level: 3 },
              { id: '10083', name: '连衣裙', parentId: '1008', platform: 'mercari', level: 3 },
              { id: '10084', name: '外套', parentId: '1008', platform: 'mercari', level: 3 },
              { id: '10085', name: '套装', parentId: '1008', platform: 'mercari', level: 3 },
              { id: '10086', name: '其他', parentId: '1008', platform: 'mercari', level: 3 }
            ]
          }
        ]
      },
      {
        id: '2000',
        name: '电子产品',
        parentId: '',
        platform: 'mercari',
        level: 1,
        children: [
          { id: '2001', name: '手机数码', parentId: '2000', platform: 'mercari', level: 2 },
          { id: '2002', name: '电脑办公', parentId: '2000', platform: 'mercari', level: 2 },
          { id: '2003', name: '家用电器', parentId: '2000', platform: 'mercari', level: 2 }
        ]
      },
      {
        id: '3000',
        name: '家居生活',
        parentId: '',
        platform: 'mercari',
        level: 1,
        children: [
          { id: '3001', name: '家具', parentId: '3000', platform: 'mercari', level: 2 },
          { id: '3002', name: '家纺', parentId: '3000', platform: 'mercari', level: 2 },
          { id: '3003', name: '厨具', parentId: '3000', platform: 'mercari', level: 2 }
        ]
      }
    ],
    'yahoo_used': [
      { id: '2001', name: '个护健康', parentId: '', platform: 'yahoo_used', level: 1 },
      { id: '2002', name: '美妆护肤', parentId: '', platform: 'yahoo_used', level: 1 },
      { id: '2003', name: '香水', parentId: '', platform: 'yahoo_used', level: 1 }
    ],
    'yahoo_auction': [
      { id: '3001', name: '电子产品', parentId: '', platform: 'yahoo_auction', level: 1 },
      { id: '3002', name: '动漫周边', parentId: '', platform: 'yahoo_auction', level: 1 },
      { id: '3003', name: '游戏', parentId: '', platform: 'yahoo_auction', level: 1 }
    ],
    'rakuma': [
      { id: '4001', name: '母婴用品', parentId: '', platform: 'rakuma', level: 1 },
      { id: '4002', name: '玩具', parentId: '', platform: 'rakuma', level: 1 }
    ]
  }
  
  return mockPlatformCategories[platform] || []
}

// 递归搜索分类名称
function findCategoryByName(categories: any[], targetName: string): any | null {
  for (const category of categories) {
    if (category.name === targetName) {
      return category
    }
    if (category.children && category.children.length > 0) {
      const found = findCategoryByName(category.children, targetName)
      if (found) return found
    }
  }
  return null
}

// 递归搜索分类ID
function findCategoryById(categories: any[], targetId: string): any | null {
  console.log(`搜索分类ID: ${targetId}，当前分类数量: ${categories.length}`)
  
  for (const category of categories) {
    console.log(`检查分类: ${category.id} (${category.name})`)
    
    if (category.id === targetId) {
      console.log(`找到匹配的分类: ${category.id} - ${category.name}`)
      return category
    }
    
    if (category.children && category.children.length > 0) {
      console.log(`继续搜索子分类，子分类数量: ${category.children.length}`)
      const found = findCategoryById(category.children, targetId)
      if (found) return found
    }
  }
  
  console.log(`未找到ID为 ${targetId} 的分类`)
  return null
}

// 获取平台分类选项（更新为使用真实的平台分类数据）
function getPlatformCategoryOptions(currentSite: string) {
  // 从平台分类管理获取真实数据
  const platformCategories = getPlatformCategoriesFromManager(currentSite)
  
  if (!platformCategories || platformCategories.length === 0) {
    return []
  }
  
  // 将分类数据转换为级联选择器需要的格式
  function convertToCascaderFormat(categories: any[]): any[] {
    return categories.map(category => ({
      id: category.id,
      labelWithId: `${category.id} - ${category.name}`,
      children: category.children && category.children.length > 0 
        ? convertToCascaderFormat(category.children) 
        : undefined
    }))
  }
  
  return convertToCascaderFormat(platformCategories)
}

/*
  实际项目中的数据共享实现示例：
  
  // 1. 创建共享的category store (src/store/categoryStore.ts)
  import { defineStore } from 'pinia'
  
  export const useCategoryStore = defineStore('category', {
    state: () => ({
      platformCategories: {} as Record<string, Category[]>,
      loading: false,
      lastUpdate: null as Date | null
    }),
    
    actions: {
      async fetchPlatformCategories(platform: string) {
        this.loading = true
        try {
          // 调用API获取平台分类数据
          const response = await api.getPlatformCategories(platform)
          this.platformCategories[platform] = response.data
          this.lastUpdate = new Date()
        } catch (error) {
          console.error('获取平台分类失败:', error)
        } finally {
          this.loading = false
        }
      },
      
      getPlatformCategories(platform: string): Category[] {
        return this.platformCategories[platform] || []
      }
    }
  })
  
  // 2. 在平台分类管理页面中使用
  import { useCategoryStore } from '@/store/categoryStore'
  const categoryStore = useCategoryStore()
  
  // 获取分类数据
  const categories = computed(() => categoryStore.getPlatformCategories(selectedPlatform.value))
  
  // 3. 在平台映射页面中使用
  import { useCategoryStore } from '@/store/categoryStore'
  const categoryStore = useCategoryStore()
  
  // 获取平台分类数据
  function getPlatformCategoriesFromManager(platform: string): Category[] {
    return categoryStore.getPlatformCategories(platform)
  }
  
  这样两个页面就能共享同一套数据，确保数据的一致性和实时性。
*/

// 当输入类目名称时触发
function onCategoryNamesInput() {
  // 清空ID输入框，避免数据不一致
  if (mappingForm.platformCategoryNames.trim()) {
    mappingForm.platformCategoryIds = ''
  }
}

// 当输入类目ID时触发
function onCategoryIdsInput() {
  // 清空名称输入框，避免数据不一致
  if (mappingForm.platformCategoryIds.trim()) {
    mappingForm.platformCategoryNames = ''
  }
}

// 当类目名称输入框失去焦点时，自动抓取对应的ID
async function fetchCategoryIds() {
  const names = mappingForm.platformCategoryNames.trim()
  if (!names || mappingForm.platformCategoryIds.trim()) return
  
  const categoryNames = names.split(',').map(s => s.trim()).filter(Boolean)
  if (categoryNames.length === 0) return
  
  try {
    const ids = await fetchCategoryIdsFromNames(categoryNames, mappingForm.platform)
    if (ids.length > 0) {
      mappingForm.platformCategoryIds = ids.join(',')
      // ElMessage.success('已自动抓取对应的类目ID') // ElMessage is not imported, so this line is commented out
    }
  } catch (error) {
    console.error('抓取类目ID失败:', error)
    // ElMessage.warning('抓取类目ID失败，请手动输入') // ElMessage is not imported, so this line is commented out
  }
}

// 当类目ID输入框失去焦点时，自动抓取对应的名称
async function fetchCategoryNames() {
  const ids = mappingForm.platformCategoryIds.trim()
  if (!ids || mappingForm.platformCategoryNames.trim()) return
  
  const categoryIds = ids.split(',').map(s => s.trim()).filter(Boolean)
  if (categoryIds.length === 0) return
  
  try {
    const names = await fetchCategoryNamesFromIds(categoryIds, mappingForm.platform)
    if (names.length > 0) {
      mappingForm.platformCategoryNames = names.join(',')
      // ElMessage.success('已自动抓取对应的类目名称') // ElMessage is not imported, so this line is commented out
    }
  } catch (error) {
    console.error('抓取类目名称失败:', error)
    // ElMessage.warning('抓取类目名称失败，请手动输入') // ElMessage is not imported, so this line is commented out
  }
}
function exportExcel() {
  alert('导出功能（mock）：已导出全部映射关系')
}
function downloadTemplate() {
  // 生成Excel模板，6列表头+1行样例
  const header = ['本地分类ID','本地分类名称','本地分类路径','平台ID','平台名称','平台类目']
  const example = [1, '服饰', '服饰', 'mercari', '煤炉', '女装,男装']
  const ws = XLSX.utils.aoa_to_sheet([header, example])
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '平台映射模板')
  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
  const blob = new Blob([wbout], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = '平台映射导入模板.xlsx'
  a.click()
  URL.revokeObjectURL(url)
}
function importExcel() {
  showImportModal.value = true
  importResult.value = ''
}
function handleImportFile(e: Event) {
  const file = (e.target as HTMLInputElement).files?.[0]
  if (!file) return
  const reader = new FileReader()
  reader.onload = (evt) => {
    const data = evt.target?.result
    const workbook = XLSX.read(data, { type: 'array' })
    const sheet = workbook.Sheets[workbook.SheetNames[0]]
    const rows = XLSX.utils.sheet_to_json(sheet, { header: 1 })
    // 解析数据
    let count = 0
    for (let i = 1; i < rows.length; i++) {
      const row = rows[i] as string[]
      if (!row || row.length < 7) continue
      const localCategoryId = Number(row[0])
      // const localCategoryName = String(row[1])
      // const localCategoryPath = String(row[2])
      const platform = String(row[3])
      // const platformName = String(row[4])
      const names = String(row[5]).split(',').map(s=>s.trim()).filter(Boolean)
      const ids = String(row[6]).split(',').map(s=>s.trim()).filter(Boolean)
      if (!localCategoryId || !platform || !names.length || !ids.length) continue
      if (names.length !== ids.length) {
        importResult.value += `第 ${i+1} 行平台类目和ID数量不匹配，跳过。\n`
        continue
      }
      const existIdx = mappings.value.findIndex(m => m.localCategoryId == localCategoryId && m.platform === platform)
      if (existIdx > -1) {
        mappings.value[existIdx].platformCategoryNames = names
        mappings.value[existIdx].platformCategoryIds = ids
      } else {
        mappings.value.push({ id: Date.now() + i, localCategoryId, platform, platformCategoryNames: names, platformCategoryIds: ids })
      }
      count++
    }
    importResult.value = `成功导入 ${count} 条映射关系！`
  }
  reader.readAsArrayBuffer(file)
}


</script>

<style scoped>
.main-content {
  width: 100vw;
  min-width: 0;
  padding: 0 24px 24px 0;
  background: #f1f5f9;
  min-height: calc(100vh - var(--header-height));
  margin: 0;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  box-sizing: border-box;
}
.panel {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.03);
  overflow: hidden;
  margin: 0;
  width: 100%;
  max-width: 100%;
}
.panel-header {
  padding: 20px 24px 16px 24px;
  border-bottom: 1px solid #e2e8f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}
.panel-title {
  font-size: 18px;
  font-weight: 600;
  color: #2b2d42;
}
.panel-body {
  padding: 20px 24px 24px 24px;
  overflow-x: auto;
}
.btn-primary {
  background: #4361ee;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
}
.btn-primary:hover {
  background: #3a56d4;
}
.action-btn {
  background: #f4f6fb;
  color: #4361ee;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  padding: 3px 12px;
  font-size: 13px;
  margin-right: 6px;
  cursor: pointer;
}
.action-btn.danger {
  background: #fbe9e9;
  color: #e63946;
  border: 1px solid #f5c2c7;
}
.mapping-badge {
  background: #eaf7f0;
  color: #2dba4e;
  border-radius: 6px;
  padding: 3px 10px;
  margin-right: 8px;
  font-size: 13px;
  display: inline-block;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}
.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: rgba(0,0,0,0.18);
  z-index: 99;
  display: flex;
  align-items: center;
  justify-content: center;
}
.modal-form {
  background: #fff;
  border-radius: 12px;
  padding: 32px;
  min-width: 340px;
  max-width: 96vw;
  box-shadow: 0 8px 32px rgba(67,97,238,0.12);
  display: flex;
  flex-direction: column;
  gap: 18px;
}
.modal-actions {
  display: flex;
  gap: 12px;
  margin-top: 8px;
  flex-wrap: wrap;
}
.form-group {
  margin-bottom: 16px;
}
.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #333;
}
.form-group input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}
.form-group input:focus {
  outline: none;
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
.input-tip {
  font-size: 12px;
  color: #6c757d;
  margin-top: 4px;
  font-style: italic;
}
/* 响应式适配 */
@media (max-width: 1200px) {
  .main-content {
    padding-right: 8px;
  }
  .panel-header, .panel-body {
    padding-left: 12px;
    padding-right: 12px;
  }
}
@media (max-width: 768px) {
  .main-content {
    padding: 0 2px 12px 0;
  }
  .panel-header, .panel-body {
    padding-left: 4px;
    padding-right: 4px;
  }
  .panel-title {
    font-size: 16px;
  }
  .modal-form {
    padding: 12px;
    min-width: 0;
    max-width: 100vw;
  }
  .panel-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .btn-primary, .action-btn {
    font-size: 13px;
    padding: 6px 10px;
  }
  table {
    font-size: 13px;
  }
}
@media (max-width: 500px) {
  .main-content {
    padding: 0 0 6px 0;
  }
  .panel-body, .panel-header {
    padding: 2px;
  }
  .modal-form {
    padding: 4px;
  }
}
</style> 